package com.yantong.quartz.job;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yantong.enums.PayChannelEnum;
import com.yantong.mapper.CentreMapper;
import com.yantong.constant.OrderStatus;
import com.yantong.constant.PayStatus;
import com.yantong.pojo.PayChannel;
import com.yantong.service.PayChannelService;
import com.yantong.pojo.Order;
import com.yantong.service.OrderService;
import com.yantong.service.PayService;
import com.yantong.service.MemberService;
import com.yantong.utils.payment.Scan_OrderQuery;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 *
 * @author kanghaixin
 * @date 2018/9/14.17:24
 */
public class OrderNoPyJob implements Job {

    private static final Logger logger = LoggerFactory.getLogger(OrderNoPyJob.class);
    
    @Autowired
	private PayService payService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private CentreMapper centreMapper;
	@Autowired
	PayChannelService payChannelService;
	@Autowired
	OrderService orderService;
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException{
        Object data = jobExecutionContext.getJobDetail().getJobDataMap().get("jobData");
    	logger.info("=====进来跑p====");

        if (data == null) {
            logger.info("job data is null,please check!");
            return;
        }
        logger.info("=====进来跑2====");
//        OrderService orderService = ApplicationContextRegister.getBean(OrderService.class);
        Order order = orderService.getByKey((Long) data);
        if (order == null) {
            logger.info("order info is null,please check!");
            return;
        }
        logger.info("=====进来跑3====");
        //第三方支付没有及时回调补助机制start
        if(order.getPaystatus()==PayStatus.PAYING.getCode()&&OrderStatus.wait_pay.getCode() == order.getStatus()){
        	
			logger.info("======================查询下单支付接口==========================="+order.getStatus());

        /*	//如果订单支付状态处于支付中，则查询第三方
        	PayQueryResVo req = new PayQueryResVo();
    		req.setSpid(ConfigUtil.getProperty("TFB_spid"));
    		req.setSpBillno(order.getOutTradeNo());*/
        	try {
        		PayChannel payChannel = payChannelService.getFirstChannel(order.getCentreId());
        		
        		if (StringUtils.isNotBlank(payChannel.getChannelCode()) && payChannel.getChannelCode().equals(PayChannelEnum.SXF.getCode())) {

        			
        		}else {
					//Map<String, Object> queryPaySigleMap = TFBPayUtil.getQueryPaySigleConfig(req);
	        		//汇聚订单查询
	        		Map<String, Object> queryPaySigleMap = Scan_OrderQuery.scanOrder(order.getOutTradeNo());
					//如果支付成功走回调逻辑
					/*if(null != queryPaySigleMap && Integer.parseInt(queryPaySigleMap.get("state")+"")==3){*/
	        		if(null != queryPaySigleMap && Integer.parseInt(queryPaySigleMap.get("ra_Status")+"")==100){
						logger.info("======================异步没有通知主动发起查询下单支付接口状态==========================="+queryPaySigleMap.get("state")+"");
						
						//已支付状态 后 不继续回调
						if(order != null && order.getStatus()>=1){
							return ;
						}
						logger.info("======================异步没有通知主动发起查询order.getPayattach()==========================="+order.getPayattach());
						JSONObject attach = JSON.parseObject(order.getPayattach());
						int result = -1;
						int payType = attach.getIntValue("type");
//						if (payType == ApiController.WXPAY_ORDER) {
						if (payType == 0) {
							Long orderId = attach.getLong("orderId");
							//根据订单编号更新订单支付通道信息
	//						Map<String, Object>updMap = new HashMap<>();
	//						updMap.put("orderId", orderId);
	//						updMap.put("chanelcode", PayChannelEnum.TFB.getCode());//通道编号
	//						updMap.put("chanelname", PayChannelEnum.TFB.getValue());//通道名称
	//						orderService.updateOrderChannelByMap(updMap);
							
							result = payService.wxPay(orderId, queryPaySigleMap.get("r5_TrxNo")+"",queryPaySigleMap.get("r2_OrderNo")+"", attach.getInteger("points"),0L);
							
							logger.info("======================主动查询天付宝业务逻辑处理完==========================="+result);
	
							if (result > 0) {
								//this.sendPayNotify(orderId);
							}
				        	return;
				        	
//						} else if (payType == ApiController.WXPAY_VIP) {
						} else if (payType ==1) {
							logger.error("补救机制进来购买vip逻辑");
							Long memberId = attach.getLong("memberId");
							String code = attach.getString("code");
							result = memberService.buyVipWx(memberId, queryPaySigleMap.get("r5_TrxNo")+"", code);
//						}else if (payType == ApiController.WXPAY_SHIPCARD) {
						}
//						else if (payType == 2) {
//			                logger.error("补救机制进来购买充值卡逻");
//			                //购买充值卡
//			                Long memberId = attach.getLong("memberId");
//			                Long shipcardId = attach.getLong("shipcardId");
//			                result = memberService.buyShipcardWx(memberId, queryPaySigleMap.get("r5_TrxNo")+"", shipcardId);
//			            }
						if (result < 1) {
							logger.info("======================主动查询成功业务逻辑处理失败===========================");
						}
					}
        	}
        	} catch (/*DocumentException | IOException e | */Exception e) {
				e.printStackTrace();
			}
        }
      //第三方支付没有及时回调补助机制end
        
        if (OrderStatus.wait_pay.getCode() == order.getStatus()) {
            logger.info("order gt waiting over time to pay! already auto closed!");
            orderService.closeOrder(order.getId(),null, "未付款自动关闭");
            //是购买版本订单不是升级的订单
            if(order.getIsCentreord()==1 && order.getIsupgrade() != 1) {
            	//删除未付款自动关闭商户的信息
            	centreMapper.delByMidAndStu(order.getMid());
            }
        }
    }
}
